﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QButtonGroup>
#include <QFileDialog>
#include <QRadioButton>
#include <QSettings>
#include <QSplitter>
#include <QTime>
#include <QTimer>
#include <yaml-cpp/yaml.h>

TmLogger *g_TmLogger = NULL;

int g_RobotChassisLength = 80;   //机器人底盘长度 单位CM
int g_RobotChassisWidth = 53;   //机器人底盘宽度 单位CM
int g_RobotChassisRadius = 0;   //机器人底盘半径

QString g_strExeRoot = "";
QString g_LocalMapPath = "C:/maps";
QString g_RemoteMapPath = "/home/.tami/maps";
QString g_CurrentMapID = "";

QString g_map_Image;//#文件名
qreal  g_curScaleValue = 1;//当前缩放比例
double  g_map_resolution = 0.05;//#地图分辨率 单位：米/像素
bool  g_is_OpenMapEdit = false;//是否打开地图编辑
bool  g_is_OpenCreateMap = false;//是否开始创建地图
double  g_map_origin[3] = {0,0,0};//图像左下角在地图坐标下的坐标
QStringList  g_StationPointList;//当前导航路线经过的点位
QStringList  g_StationOFFPointList;//当前导航路线已经经过的点位
QString g_CurrentStationPoint;//当前导航的目的点位

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle(QString("TMRobotNavi %1").arg(APP_VERSION));
    g_strExeRoot = QCoreApplication::applicationDirPath();
    qDebug()<<"MainWindow::MainWindow thread id="<<QThread::currentThreadId()<<APP_VERSION;
    g_TmLogger = new TmLogger(g_strExeRoot);
    connect(this,SIGNAL(sig_Loger(QString)),g_TmLogger,SLOT(slot_LoggerStrAppend(QString)),Qt::QueuedConnection);
    g_TmLogger->moveToThread(&m_LoggerThread);
    m_LoggerThread.start();

    //m_DirectedGraph = new DirectedGraph("E:/maps/dating/dating.json");
    ui->pushButton_2->hide();

    ui->btn_back->installEventFilter(this);
    ui->btn_front->installEventFilter(this);
    ui->btn_left->installEventFilter(this);
    ui->btn_leftback->installEventFilter(this);
    ui->btn_leftfront->installEventFilter(this);
    ui->btn_right->installEventFilter(this);
    ui->btn_rightback->installEventFilter(this);
    ui->btn_rightfront->installEventFilter(this);
    ui->btn_stop->installEventFilter(this);

    ui->tabWidget_mapEdit->setCurrentIndex(0);

    ui->tableWidget_Task->setContextMenuPolicy (Qt::CustomContextMenu);
    connect(ui->tableWidget_Task,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(showRightmenu(QPoint)));

    QSettings CfgSet(QString("%1/BaseCfg.ini").arg(g_strExeRoot), QSettings::IniFormat);
    CfgSet.setIniCodec("UTF-8");
    if(!CfgSet.value("base/localPath").toString().isEmpty())
        g_LocalMapPath = CfgSet.value("base/localPath").toString();
    ui->lineEdit_localPath->setText(g_LocalMapPath);

    m_MapGraphicsView = new MyGraphicsView(this);
    ui->hLayout_view->addWidget(m_MapGraphicsView);
    connect(m_MapGraphicsView,SIGNAL(sig_MapMessage(QString,QString)),this,SLOT(slot_MyGraphicsView_Data(QString,QString)));
    connect(m_MapGraphicsView,SIGNAL(sig_MapLineMessage(QString,QVariantMap)),this,SLOT(slot_MyGraphicsView_LineData(QString,QVariantMap)));
    m_MapGraphicsView->installEventFilter(this);
    m_TMSSHConnectWGT = new TM_SSHConnectWGT();
    connect(m_TMSSHConnectWGT,&TM_SSHConnectWGT::sig_TcpCmdData,this,&MainWindow::slot_UpDataRemoteMapList);
    qDebug()<<"MainWindow::MainWindow="<<QThread::currentThreadId();

    m_TcpSocket = new TcpSocket(1);
    connect(m_TcpSocket,SIGNAL(sig_RevData(QString,QStringList)),this,SLOT(slot_TcpRevData(QString,QStringList)),Qt::QueuedConnection);
    connect(m_TcpSocket,SIGNAL(sig_mapTopicPgm(QPixmap)),m_MapGraphicsView,SLOT(slot_mapPixmap(QPixmap)),Qt::QueuedConnection);
    connect(m_TcpSocket,SIGNAL(sig_inConnect(bool)),m_TMSSHConnectWGT,SLOT(slot_TcpConnectStatu(bool)),Qt::QueuedConnection);
    connect(m_TcpSocket,SIGNAL(sig_Loger(QString)),g_TmLogger,SLOT(slot_LoggerStrAppend(QString)),Qt::QueuedConnection);
    connect(this,SIGNAL(sig_ConnectNavi(QString,int)),m_TcpSocket,SLOT(connectToHost(QString,int)),Qt::QueuedConnection);
    connect(this,SIGNAL(sig_NaviSendData(QString,QString)),m_TcpSocket,SLOT(slot_SocketSendData(QString,QString)),Qt::QueuedConnection);
    m_TcpSocket->moveToThread(&m_TcpThread);
    m_TcpThread.start();

    m_TcpSocket_GetCreatMap = new mapTcpSocket();
    connect(m_TcpSocket_GetCreatMap,SIGNAL(sig_RevData(QString,QStringList)),this,SLOT(slot_TcpRevData(QString,QStringList)),Qt::QueuedConnection);
    connect(m_TcpSocket_GetCreatMap,SIGNAL(sig_mapTopicPgm(QPixmap)),m_MapGraphicsView,SLOT(slot_mapPixmap(QPixmap)),Qt::QueuedConnection);
    connect(this,SIGNAL(sig_ConnectNavi(QString,int)),m_TcpSocket_GetCreatMap,SLOT(connectToHost(QString,int)),Qt::QueuedConnection);
    connect(this,SIGNAL(sig_getCreatorMapData(QString)),m_TcpSocket_GetCreatMap,SLOT(slot_getCreatorMapData(QString)),Qt::QueuedConnection);
    m_TcpSocket_GetCreatMap->moveToThread(&m_TcpThread_GetCreatMap);
    m_TcpThread_GetCreatMap.start();

    m_MapGraphicsView->slot_OpenMapEdit(false);
    ui->tab_Point->setEnabled(false);
    ui->tab_Line->setEnabled(false);
    ui->tab_map->setEnabled(false);


    ui->toolBar_Left->setEnabled(false);
    QActionGroup *p = new QActionGroup(this);
    p->addAction(ui->action_Select);
    p->addAction(ui->action_NewLine);
    p->addAction(ui->action_VirtureWall);
    p->addAction(ui->action_Eraser);
    p->addAction(ui->action_addpoint);
    p->addAction(ui->action_Location);
    p->setExclusive(true);

    QString filename = QString("%1/css/mainwindow.css").arg(g_strExeRoot);
    QFile fileSkin(filename);
    if(fileSkin.open(QIODevice::ReadOnly))
    {
        QString strSkin = QString::fromUtf8(fileSkin.readAll());
        strSkin = strSkin.replace("~", g_strExeRoot);
        this->setStyleSheet(strSkin);
        fileSkin.close();
    }

    m_Connect_Label = new QLabel(this);
    m_Connect_Label->setPixmap(QPixmap(":/image/image/red.png"));
    m_Connect_Label->setToolTip("Connect status"); // 鼠标悬停时显示的提示


    m_JiTing_Label = new QLabel(this);
    m_JiTing_Label->setPixmap(QPixmap(":/image/image/jiting.png"));
    m_JiTing_Label->setToolTip(u8"急停状态");

    m_Battery_Label = new QLabel(this);
    ui->statusBar->addWidget(m_Connect_Label);
    ui->statusBar->addWidget(m_JiTing_Label);
    ui->statusBar->addWidget(m_Battery_Label);

    m_RobotViewCen = new QLabel();


    // 创建 QSplitter 实例

    QSplitter *splitter = new QSplitter(Qt::Horizontal,this);
    // 添加 QTextEdit 控件到 QSplitter
    splitter->addWidget(ui->widget_View);
    splitter->addWidget(ui->tabWidget);

    QSplitter *splitter1 = new QSplitter(Qt::Vertical,this);
    // 添加 QTextEdit 控件到 QSplitter
    splitter1->addWidget(splitter);
    splitter1->addWidget(ui->widget_statu);

    this->setCentralWidget(splitter1);

    m_DlgCarPara = new DlgCarPara(this);
    m_DlgCarPara->setParent((void*)this);

    m_DlgLaserPara = new DlgLaserPara(this);
    m_DlgLaserPara->setParent((void*)this);

    m_DlgVisionPara = new DlgVisionPara(this);
    m_DlgVisionPara->setParent((void*)this);

    m_DlgIMUPara = new DlgIMUPara(this);
    m_DlgIMUPara->setParent((void*)this);

    m_DlgReportError = new DlgReportError(this);
    m_DlgReportError->setParent((void*)this);

    loadUI();

}

MainWindow::~MainWindow()
{
    delete ui;

    m_TcpThread.quit();
    m_TcpThread.wait();

    m_TcpThread_GetCreatMap.quit();
    m_TcpThread_GetCreatMap.wait();
    if(m_TcpSocket)
    {   delete m_TcpSocket;
        m_TcpSocket = nullptr;
    }
    if(m_TcpSocket_GetCreatMap)
    {   delete m_TcpSocket_GetCreatMap;
        m_TcpSocket_GetCreatMap = nullptr;
    }
    if(m_TMSSHConnectWGT != nullptr)
    {
        m_TMSSHConnectWGT->deleteLater();
        m_TMSSHConnectWGT = nullptr;
    }

    m_LoggerThread.quit();
    m_LoggerThread.wait();
    if(g_TmLogger)
    {   delete g_TmLogger;
        g_TmLogger = nullptr;
    }

    delete m_RobotViewCen;
}

void MainWindow::loadUI()
{
    WgtPara *m_Reverse = new WgtPara(2,"倒向","Reverse",this);
    ui->gridLayout_LinePara->addWidget(m_Reverse,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_Reverse,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["Reverse"] = m_Reverse;

    WgtPara *m_Detour = new WgtPara(2,"避障","Detour",this);
    ui->gridLayout_LinePara->addWidget(m_Detour,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_Detour,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["Detour"] = m_Detour;

    WgtPara *m_maxSpeed = new WgtPara(1,"最大速度(m/s)","maxSpeed",this);
    ui->gridLayout_LinePara->addWidget(m_maxSpeed,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_maxSpeed,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["maxSpeed"] = m_maxSpeed;

    WgtPara *m_maxAddSpeed = new WgtPara(1,"最大加速度(m/s)","maxAddSpeed",this);
    ui->gridLayout_LinePara->addWidget(m_maxAddSpeed,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_maxAddSpeed,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["maxAddSpeed"] = m_maxAddSpeed;

    WgtPara *m_maxSubSpeed = new WgtPara(1,"最大减速度(m/s)","maxSubSpeed",this);
    ui->gridLayout_LinePara->addWidget(m_maxSubSpeed,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_maxSubSpeed,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["maxSubSpeed"] = m_maxSubSpeed;

    WgtPara *m_maxRotaSpeed = new WgtPara(1,"最大旋转速度(m/s)","maxRotaSpeed",this);
    ui->gridLayout_LinePara->addWidget(m_maxRotaSpeed,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_maxRotaSpeed,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["maxRotaSpeed"] = m_maxRotaSpeed;

    WgtPara *m_maxRotaAddSpeed = new WgtPara(1,"最大旋转加速度(m/s)","maxRotaAddSpeed",this);
    ui->gridLayout_LinePara->addWidget(m_maxRotaAddSpeed,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_maxRotaAddSpeed,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["maxRotaAddSpeed"] = m_maxRotaAddSpeed;

    WgtPara *m_maxRotaSubSpeed = new WgtPara(1,"最大旋转减速度(m/s)","maxRotaSubSpeed",this);
    ui->gridLayout_LinePara->addWidget(m_maxRotaSubSpeed,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_maxRotaSubSpeed,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["maxRotaSubSpeed"] = m_maxRotaSubSpeed;

    WgtPara *m_ultrasonic = new WgtPara(2,"是否开启超声","ultrasonic",this);
    ui->gridLayout_LinePara->addWidget(m_ultrasonic,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_ultrasonic,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["ultrasonic"] = m_ultrasonic;

    WgtPara *m_laser = new WgtPara(2,"是否开启激光避障","laser",this);
    ui->gridLayout_LinePara->addWidget(m_laser,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_laser,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["laser"] = m_laser;

    WgtPara *m_fallingdown = new WgtPara(2,"是否开启防跌落","fallingdown",this);
    ui->gridLayout_LinePara->addWidget(m_fallingdown,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_fallingdown,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["fallingdown"] = m_fallingdown;

    WgtPara *m_ingraed = new WgtPara(2,"是否开启红外","ingraed",this);
    ui->gridLayout_LinePara->addWidget(m_ingraed,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_ingraed,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["ingraed"] = m_ingraed;

    WgtPara *m_virualLaser = new WgtPara(2,"是否开启虚拟激光","virualLaser",this);
    ui->gridLayout_LinePara->addWidget(m_virualLaser,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_virualLaser,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["virualLaser"] = m_virualLaser;

    WgtPara *m_3DCameraObstacle = new WgtPara(2,"是否开启3D相机障碍物检测","3DCameraObstacle",this);
    ui->gridLayout_LinePara->addWidget(m_3DCameraObstacle,ui->gridLayout_LinePara->rowCount(),0,1,3);
    connect(m_3DCameraObstacle,&WgtPara::sig_ParaData,this,&MainWindow::slot_ParaData);
    m_LiniPataMap["3DCameraObstacle"] = m_3DCameraObstacle;
}

void MainWindow::slot_UpDataRemoteMapList(QString Type,QString data)
{
    qDebug()<<"slot_UpDataRemoteMapList="<<Type<<data;

    if(Type == "TcpCon")
    {
        emit sig_ConnectNavi(data,9090);
    }
    else if(Type == "TcpDis")
    {
        emit sig_ConnectNavi("",0);
        m_Connect_Label->setPixmap(QPixmap(":/image/image/red.png"));
        ui->label_statu->setText(QString(u8"未连接"));
    }
    else if(Type == "GetMapList")
    {
        qDebug()<<"sssssssssssssssssss"<<data;
        QStringList dataList = data.split(",",Qt::SkipEmptyParts);
        ui->listWidget_Local->clear();
        ui->listWidget_Remote->clear();
        for(int i=0;i<dataList.length();i++)
        {
            QString data = QString(dataList[i]);
            data.replace(" ","");
            int row = ui->listWidget_Remote->count();
            ui->listWidget_Remote->insertItem(row,new QListWidgetItem(data));
        }

        QDir dir(g_LocalMapPath);
        QStringList filesList = dir.entryList(QDir::Dirs);
        for(int i=0;i<filesList.length();i++)
        {
            if(!QString(filesList[i]).contains("."))
            {
                int row = ui->listWidget_Local->count();
                ui->listWidget_Local->insertItem(row,new QListWidgetItem(QString(filesList[i])));
            }
        }
    }

    else if(Type == "pub_pushPull")
    {
        ui->btn_pull->setEnabled(true);
        ui->btn_Push->setEnabled(true);
        if(data.startsWith("openMap:"))
        {
            QString fileName = data.remove(0,8);
            qDebug()<<"----------------------------"<<fileName;
            QDir dir(fileName);
            if (dir.exists())
            {
                ui->label_currentMap->setText(fileName);
                slot_loadMapFiles(fileName);
            }
        }
        else
            slot_ShowMessageDlg("File transfer",data == "true" ? "ssh File transfer successful" : "ssh File transfer failed",5000);

    }

    else if(Type == "pullAmtYAML")
    {
        if(data == "true")
        {
            m_DlgCarPara->slot_loadAmrYAML();
            m_DlgLaserPara->slot_loadAmrYAML();
            m_DlgVisionPara->slot_loadAmrYAML();
            m_DlgIMUPara->slot_loadAmrYAML();
        }
    }
}

void MainWindow::slot_MyGraphicsView_Data(QString Type, QString data)
{
    if(Type == "MoucePinot")
        ui->label_moucePoint->setText(data);
    else if(Type == "action_SelectSetChecked")
    {
        ui->action_Select->setChecked(true);
        m_MapGraphicsView->slot_CurrentAction(Action_NULL);
    }

    else if(Type =="HandLocalization")
    {
        emit sig_NaviSendData("",data);
    }
}

void MainWindow::slot_MyGraphicsView_LineData(QString Type, QVariantMap dataMap)
{
    ui->btn_Sendnavi->setText("执行点位导航");
    ui->btn_Sendnavi_XY->setText(QString(u8"执行坐标导航"));
    ui->label_moucePoint->setText("");
    ui->comboBox_Direct->clear();
    ui->lineEdit_LineID->setText("");
    qDebug()<<"ui->lineEdit_LineID->setText(dataMap[00";
    ui->radioButton_StartEnd->setText("");
    ui->radioButton_endStart->setText("");
    ui->checkBox_linear->setChecked(false);
    ui->horizontalSlider_Point->setValue(0);
    ui->lineEdit_Angle->setText("");
    ui->lineEdit_PointName->setText("");
    ui->lineEdit_PointX->setText("");
    ui->lineEdit_PointY->setText("");


    if(Type == "MoucePinotMess")
    {
        if(g_is_OpenMapEdit)
            ui->tabWidget_mapEdit->setCurrentIndex(1);
        ui->horizontalSlider_Point->setValue(-dataMap["rotation"].toDouble());
        ui->lineEdit_Angle->setText(QString::number(-dataMap["rotation"].toDouble()));
        ui->lineEdit_PointName->setText(dataMap["ItemId"].toString());
        QString dataXText = dataMap["pointX"].toString();
        QString dataYText = dataMap["pointY"].toString();
        dataXText = dataXText.left(dataXText.indexOf(".")+5);
        dataYText = dataYText.left(dataYText.indexOf(".")+5);
        ui->btn_Sendnavi->setText(QString(u8"执行点位导航:%1=(%2  %3)")
                                      .arg(dataMap["ItemId"].toString(),dataXText,dataYText));
        ui->lineEdit_PointX->setText(dataXText);
        ui->lineEdit_PointY->setText(dataYText);
    }
    else if(Type == "Moucebezier")
    {
        if(g_is_OpenMapEdit)
            ui->tabWidget_mapEdit->setCurrentIndex(2);
        QStringList dataList =dataMap["ItemBezierPointID"].toString().split("->");
        qDebug()<<"ui->lineEdit_LineID->setText(dataMap[000"<<dataMap["LineitemID"].toString();
        ui->lineEdit_LineID->setText(dataMap["LineitemID"].toString());
        ui->comboBox_Direct->clear();
        if(dataList.length() == 2)
        {
            ui->comboBox_Direct->addItem(QString(dataList[0] + "->" + dataList[1]));
            ui->comboBox_Direct->addItem(QString(dataList[1] + "->" + dataList[0]));
            ui->comboBox_Direct->addItem(QString(dataList[0] + "<->" + dataList[1]));

            ui->radioButton_StartEnd->setText(QString(dataList[0] + "->" + dataList[1]));
            ui->radioButton_endStart->setText(QString(dataList[1] + "->" + dataList[0]));
            ui->radioButton_StartEnd->hide();
            ui->radioButton_endStart->hide();

            ui->comboBox_Direct->setItemData(0,QVariant::fromValue(dataMap),1);


            ui->comboBox_Direct->setCurrentIndex(dataMap["LineDirection"].toInt()-1);

            ui->checkBox_linear->setChecked(dataMap["StraightLine"].toBool());

            if(dataMap["LineDirection"].toInt() == 1 || dataMap["LineDirection"].toInt() == 3)
            {
                ui->radioButton_StartEnd->show();;
            }
            if(dataMap["LineDirection"].toInt() == 2 || dataMap["LineDirection"].toInt() == 3)
            {
                ui->radioButton_endStart->show();
            }
            if(ui->radioButton_StartEnd->isChecked())
                on_radioButton_StartEnd_clicked(true);
            else if(ui->radioButton_endStart->isChecked())
                on_radioButton_endStart_clicked(true);
        }
    }
    else if(Type == "MouceCoordinateMess")
    {
        ui->btn_Sendnavi_XY->setText(QString(u8"执行坐标导航:%1").arg(dataMap["clickpoint"].toString()));
    }


}

void MainWindow::slot_TcpRevData(QString type,QStringList dataList)
{
    if(type != g_RobotScan_multi)
    {
        //qDebug()<<"MainWindow::slot_TcpRevData:"<<type<<dataList;
        emit sig_Loger(QString("slot_TcpRevData:%1=%2").arg(type,QString(dataList.join(","))));
    }
    else
    {
        //qDebug()<<"MainWindow::slot_TcpRevData00:"<<type<<dataList.length();
        emit sig_Loger(QString("slot_TcpRevData:%1=%2").arg(type,dataList.length()));
    }

    if(ui->label_statu->text() != QString(u8"已连接"))
    {
        m_Connect_Label->setPixmap(QPixmap(":/image/image/blue.png"));
        ui->label_statu->setText(QString(u8"已连接"));
    }
    if(type == g_RobotPose && dataList.length() >= 3)
    {
        ui->label_currentPos->setText(QString("%1,%2,%3").arg(QString(dataList[0]).left(QString(dataList[0]).indexOf(".")+5)
                                                                 ,QString(dataList[1]).left(QString(dataList[1]).indexOf(".")+5)
                                                                 ,QString(dataList[2]).left(QString(dataList[2]).indexOf(".")+5)));
        m_MapGraphicsView->slot_NaviRosData(type,dataList);
    }
    else if(type == g_RobotScan_multi)
    {
        m_MapGraphicsView->slot_NaviRosData(type,dataList);
    }
    else if(type == g_RobotBattery_state)
    {
        if(dataList.length() >= 4)
        {
            QString text = QString(u8"   电源状态: ");
            if(QString(dataList[1]).startsWith("-"))
            {
                dataList[1] = QString(dataList[1]).remove(0,1);
                text += QString(u8"未充电  ");
                ui->label_batteryStatu->setText(QString(u8"未充电"));
            }
            else
            {
                text += QString(u8"充电中  ");
                ui->label_batteryStatu->setText(QString(u8"充电中"));
            }
            text += QString(u8"电压:%1V  电流:%2A  温度:%3°  剩余电量:%4%  ")
                        .arg(QString(dataList[0]),QString(dataList[1]),QString(dataList[2]),QString(dataList[3]));
            //ui->statusBar->showMessage(text);
            m_Battery_Label->setText(text);
        }
    }

    else if(type == g_RobotLocalization)
    {
        QString fileName = g_LocalMapPath+QString("/%1").arg(QString(dataList[0]));
        m_TMSSHConnectWGT->Public_ssh_Pull(QString(dataList[0]),"openMap:"+fileName);
        qDebug()<<"start_localizationfilename="<<fileName;
        // QDir dir(fileName);
        // if (dir.exists())
        // {
        //     ui->label_currentMap->setText(fileName);
        //     slot_loadMapFiles(fileName);
        // }
        // else {
        //     m_TMSSHConnectWGT->Public_ssh_Pull(QString(dataList[0]),"openMap:"+fileName);
        // }
    }

    else if(type == g_RobotNavi_status)
    {
        if(QString(dataList[0]).startsWith("arrivePoint:"))
        {
            ui->label_stationStatu->setText(QString(dataList[0]));
            if(ui->btn_Task->text() == QString(u8"停止任务"))
            {
                QTimer::singleShot(5000,this,[this](){
                    QString stationStr =  ui->label_stationStatu->text();
                    QString arrivesPoint = stationStr.remove(0,stationStr.indexOf(":")+1);
                    bool is_Have = false;
                    for(int i=0;i<ui->tableWidget_Task->rowCount();i++)
                    {
                        if(ui->tableWidget_Task->item(i,0)->text() == arrivesPoint)
                        {
                            i == ui->tableWidget_Task->rowCount()-1 ? i=0:i++;
                            is_Have = true;
                        }
                        qDebug()<<"is_Have =  "<<is_Have<<i;
                        if(is_Have && ui->tableWidget_Task->item(i,0)->text().length() > 0)
                        {
                            QString data = QString("R\"({\"op\": \"call_service\",\"service\": \"%1\",\"args\":{\"request\": \"%2:%3\",\"mode\": 2}})\";")
                                               .arg(g_RobotRequest_service,g_CurrentMapID,ui->tableWidget_Task->item(i,0)->text());//mode: 1自由导航 2路线导航
                            emit sig_NaviSendData("",data);
                            break;
                        }
                    }
                });


            }
        }

    }
    else if(type == g_RobotRequest_service)
    {
        ui->label_stationStatu->setText(QString(dataList[0]));
        if(QString(dataList[0]).startsWith("goPoint:"))
        {
        }
        else if(QString(dataList[0]) == "stop Navigation task")
        {

        }
        else if(QString(dataList[0]) == "continue Navigation task")
        {

        }
        else if(QString(dataList[0]) == "cancel Navigation task")
        {

        }
        slot_ShowMessageDlg("Navigation task",QString(dataList[0]),1000);
    }
    else if(type == g_RobotEquipmentStatu)
    {
        if(dataList.length() >= 3)
        {
            m_DlgReportError->slot_Executive(QString(dataList[0]),QString(dataList[1]),QString(dataList[2]));
            if(QString(dataList[0]) == "bkDriveStatu")
            {
                if(QString(dataList[2]).contains("32"))
                {
                    if(!QString(dataList[2]).contains("33") || !QString(dataList[2]).contains("34"))
                    {
                        m_JiTing_Label->setPixmap(QPixmap(":/image/image/jitingtrue.png"));
                        ui->label_CrashStop->setText("ON");
                    }
                    else
                    {
                        m_JiTing_Label->setPixmap(QPixmap(":/image/image/jiting.png"));
                        ui->label_CrashStop->setText("OFF");
                    }
                }
            }

        }
    }
    else if(type == g_Robot_linearOrang_speed)
    {
        //line,age   speed
        ui->label_speed->setText(dataList[0]);
    }
    else if(type == g_Robot_localization_accuracy)
    {
        ui->label_localization_accuracy->setText(dataList[0]);
    }
    else if(type == "TcpError")
    {
        m_DlgReportError->slot_Executive(type,type,dataList[0]);
        slot_ShowMessageDlg(type,dataList[0],3000);
    }
}

void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
    return;
    QMenu *pMenu = new QMenu(this);
    QAction *select = new QAction(tr("左侧工具栏"));
    select->setCheckable(true);
    select->setChecked(!ui->toolBar_Left->isHidden());
    pMenu->addAction(select);
    connect(select, &QAction::triggered,[this](){
        ui->toolBar_Left->setHidden(!ui->toolBar_Left->isHidden());
    });
    pMenu->exec(QCursor::pos());
    event->accept();
}

void MainWindow::showRightmenu(QPoint point)
{
    QMenu menu(this);
    QAction *action = menu.addAction("insert");
    QAction *action2 = menu.addAction("delete");
    // 连接动作信号到槽
    connect(action, &QAction::triggered, this, [&](){
        // 执行动作
        int row = ui->tableWidget_Task->rowCount();
        if (ui->tableWidget_Task->itemAt(point))
            row = ui->tableWidget_Task->itemAt(point)->row();
        ui->tableWidget_Task->insertRow(row);
        ui->tableWidget_Task->setItem(row,0,new QTableWidgetItem());
    });
    connect(action2, &QAction::triggered, this, [&](){
        // 执行动作
        QTableWidgetItem* item = ui->tableWidget_Task->itemAt(point);
        if (item) {
            int row = item->row();
            ui->tableWidget_Task->removeRow(row);
        }
    });

    // 显示右键菜单
    menu.exec(QCursor::pos());
}

void MainWindow::slot_loadMapFiles(QString filePath)
{
    m_MapGraphicsView->on_LoadMapfilePath(filePath);
    ui->lineEdit_MapName->setText(g_CurrentMapID);
    ui->label_mapresolution->setText(QString::number(g_map_resolution));
    ui->label_maporigin->setText(QString("[%1,%2,%3]").arg(g_map_origin[0]).arg(g_map_origin[1]).arg(g_map_origin[2]));
    ui->action_Robot->setChecked(true);
    m_MapGraphicsView->slot_Map_Edit("robotshow","true");
}

void MainWindow::slot_ParaData(QString text, QString data)
{
    qDebug()<<"MainWindow::slot_ParaData="<<text<<data;
    if(data == "NULL")
        data = "";
    //倒行
    if(ui->radioButton_StartEnd->isChecked())
    {
        m_MapGraphicsView->slot_Map_Edit(QString("%1:start->end%2").arg(text,ui->lineEdit_LineID->text()),data);
    }
    else if(ui->radioButton_endStart->isChecked())
    {
        m_MapGraphicsView->slot_Map_Edit(QString("%1:end->start%2").arg(text,ui->lineEdit_LineID->text()),data);
    }
}

void MainWindow::slot_ShowMessageDlg(QString Titie,QString text,int ms)
{
    QMessageBox messageBox(QMessageBox::Information,Titie,text, QMessageBox::Ok, this);
    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, &messageBox, &QMessageBox::accept);
    timer.setSingleShot(true);
    if(ms > 0)
        timer.start(ms);
    messageBox.exec();
}

void MainWindow::on_actionOpenMap_triggered()
{
    qDebug()<<"MainWindow::on_actionOpenMap_triggered()"<<QThread::currentThreadId();
    QString fileName = QFileDialog::getExistingDirectory(this,QStringLiteral("请选择一个文件"),g_LocalMapPath);
    if (!fileName.isEmpty())
    {
        // 用户选择了一个文件夹，可以在这里进行相应的操作
        qDebug() << "Selected file: " << fileName;
        slot_loadMapFiles(fileName);
    }
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        qDebug()<<"eventFilter Clicl="<<obj->objectName();
        if(obj == ui->btn_front)
        {
            emit sig_NaviSendData("ControlMove","front");
        }
        else if(obj == ui->btn_back)
        {
            emit sig_NaviSendData("ControlMove","back");
        }
        else if(obj == ui->btn_left)
        {
            emit sig_NaviSendData("ControlMove","left");
        }
        else if(obj == ui->btn_right)
        {
            emit sig_NaviSendData("ControlMove","right");
        }
        else if(obj == ui->btn_leftfront)
        {
            emit sig_NaviSendData("ControlMove","leftfront");
        }
        else if(obj == ui->btn_leftback)
        {
            emit sig_NaviSendData("ControlMove","leftback");
        }
        else if(obj == ui->btn_rightfront)
        {
            emit sig_NaviSendData("ControlMove","rightfront");
        }
        else if(obj == ui->btn_rightback)
        {
            emit sig_NaviSendData("ControlMove","rightback");
        }
        else if(obj == ui->btn_stop)
        {
            emit sig_NaviSendData("ControlMove","stop");
        }

    }
    else if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Delete && g_is_OpenMapEdit) {
            // 处理删除键事件
            qDebug() << "Backspace key pressed";
            m_MapGraphicsView->slot_Map_Edit("DelPointLine");
            return true; // 返回true表示事件已被处理
        }
    }
    return QMainWindow::eventFilter(obj,event);
}

void MainWindow::on_actionSaveMap_triggered()
{
    QMessageBox messwarn;
    messwarn.setIcon(QMessageBox::Warning);
    messwarn.setWindowTitle(tr("Warning消息框"));
    messwarn.setText(QString(tr("是否要保存并推送地图？")));
    messwarn.addButton(QMessageBox::Yes)->setText(u8"保存并推送");
    messwarn.addButton(QMessageBox::Save)->setText(u8"保存");
    messwarn.addButton(QMessageBox::Cancel)->setText(u8"取消");
    messwarn.setDefaultButton(QMessageBox::Cancel);

    int result = messwarn.exec();

    if(result == QMessageBox::Yes)
    {
        m_MapGraphicsView->slot_SaveMap(g_LocalMapPath+QString("/%1").arg(g_CurrentMapID));
        m_TMSSHConnectWGT->Public_ssh_Push(g_CurrentMapID);
    }
    else if(result == QMessageBox::Save)
    {
        m_MapGraphicsView->slot_SaveMap(g_LocalMapPath+QString("/%1").arg(g_CurrentMapID));
    }
}

void MainWindow::on_horizontalSlider_Point_sliderMoved(int position)
{
    m_MapGraphicsView->slot_Map_Edit("Rotation",QString::number(-position));
    ui->lineEdit_Angle->setText(QString::number(position));
}

void MainWindow::on_actionConnect_triggered()
{
    m_TMSSHConnectWGT->exec();
}

void MainWindow::on_lineEdit_Angle_returnPressed()
{
    m_MapGraphicsView->slot_Map_Edit("Rotation","-"+ui->lineEdit_Angle->text());
    ui->horizontalSlider_Point->setValue(ui->lineEdit_Angle->text().toDouble());
}

void MainWindow::on_lineEdit_PointName_returnPressed()
{
    m_MapGraphicsView->slot_Map_Edit("PointName",ui->lineEdit_PointName->text());

}

void MainWindow::on_btn_MapUpdate_clicked()
{
    ui->lineEdit_localPath->setText(g_LocalMapPath);
    ui->listWidget_Local->clear();
    ui->listWidget_Remote->clear();
    m_TMSSHConnectWGT->Pub_executeCmd(QString("ls %1").arg(g_RemoteMapPath));
}

void MainWindow::on_btn_Push_clicked()
{

    if(ui->listWidget_Local->currentRow() >= 0)
    {
        ui->btn_pull->setEnabled(false);
        ui->btn_Push->setEnabled(false);
        m_TMSSHConnectWGT->Public_ssh_Push(ui->listWidget_Local->item(ui->listWidget_Local->currentRow())->text());
    }
}

void MainWindow::on_btn_pull_clicked()
{
    if(ui->listWidget_Remote->currentRow() >= 0)
    {
        ui->btn_pull->setEnabled(false);
        ui->btn_Push->setEnabled(false);
        m_TMSSHConnectWGT->Public_ssh_Pull(ui->listWidget_Remote->item(ui->listWidget_Remote->currentRow())->text());
    }
}

void MainWindow::on_btn_PointDel_clicked()
{
    m_MapGraphicsView->slot_Map_Edit("DelPoint");
}

void MainWindow::on_btn_LineDel_clicked()
{
    m_MapGraphicsView->slot_Map_Edit("DelLine");
}

void MainWindow::on_btn_Sendnavi_clicked()
{
    if(m_MapGraphicsView->m_scene->selectedItems().length() == 1)
    {
        QGraphicsItem* item=m_MapGraphicsView->m_scene->selectedItems().at(0);
        if(item->data(ItemDesciption).toString() == ItemDesciption_Point)
        {
            QString data = QString("R\"({\"op\": \"call_service\",\"service\": \"%1\",\"args\":{\"request\": \"%2:%3\",\"mode\": 2}})\";")
                               .arg(g_RobotRequest_service,g_CurrentMapID,item->data(ItemId).toString());//mode: 1自由导航 2路线导航
            emit sig_NaviSendData("",data);
            g_StationPointList.clear();
        }
    }
}

void MainWindow::on_comboBox_Direct_activated(int index)
{
    qDebug()<<"don_comboBox_Direct_activated"<<index;
    m_MapGraphicsView->slot_Map_Edit("LineDirect",QString::number(index+1));

    ui->radioButton_StartEnd->hide();
    ui->radioButton_endStart->hide();
    if(index == 0 || index == 2)
    {
        ui->radioButton_StartEnd->show();
    }
    if(index == 1 || index == 2)
    {
        ui->radioButton_endStart->show();
    }
}

void MainWindow::on_btn_Sendnavi_XY_clicked()
{
    QString data = ui->btn_Sendnavi_XY->text();
    emit sig_NaviSendData("SendXYZMove",data.remove(0,data.indexOf(":")+1));

}

void MainWindow::on_checkBox_linear_clicked(bool checked)
{
    m_MapGraphicsView->slot_Map_Edit("StraightLine",checked ? "true" : "false");
}

void MainWindow::on_actionrobotFocus_triggered(bool checked)
{
    m_MapGraphicsView->slot_Map_Edit("ItemViewCenter","RobotView");

    static QTimer TimerId;
    if(checked)
    {
        QObject::connect(&TimerId, &QTimer::timeout, [this](){
            m_MapGraphicsView->slot_Map_Edit("ItemViewCenter","RobotView");
            // QRect rect(0,0,800,600);
            // QPixmap pixmap(rect.size());
            // pixmap.fill(Qt::transparent);
            // QPainter painter(&pixmap);
            // painter.setRenderHint(QPainter::Antialiasing);
            // painter.setRenderHint(QPainter::SmoothPixmapTransform);
            // painter.translate(-rect.topLeft());
            // QPointF datapoint = m_MapGraphicsView->m_RobotItem->pos()-QPointF(400,300);
            // m_MapGraphicsView->m_scene->render(&painter, QRectF(rect), QRectF(datapoint, rect.size()));
            // m_RobotViewCen->setPixmap(pixmap);
            // m_RobotViewCen->show();
        });
        TimerId.start(1000);
    }

    else
    {
        TimerId.stop();
        m_RobotViewCen->hide();
    }
}

void MainWindow::on_actionCreateMap_triggered()
{
    if(ui->actionCreateMap->text() == QString(u8"创建地图"))
    {
        emit sig_NaviSendData("startCreateMap");
        m_MapGraphicsView->slot_Map_Edit("newMapEdit","startCreateMap");
        ui->actionCreateMap->setText(QString(u8"结束创建地图"));
        ui->action_mapEdit->setEnabled(false);

        emit sig_NaviSendData("StopSubscribe","");
        emit sig_getCreatorMapData("startGetNewCteatorMapImage");
    }
    else if(ui->actionCreateMap->text() == QString(u8"结束创建地图"))
    {
        QString fileName;
        QMessageBox messwarn;
        messwarn.setIcon(QMessageBox::Warning);
        messwarn.setWindowTitle(tr("Warning消息框"));
        messwarn.setText(QString(tr("结束创建地图。是否要保存地图？")));
        messwarn.addButton(QMessageBox::Save)->setText(u8"结束并保存");
        messwarn.addButton(QMessageBox::Discard)->setText(u8"结束");
        messwarn.addButton(QMessageBox::Cancel)->setText(u8"取消");
        messwarn.setDefaultButton(QMessageBox::Cancel);

        QLineEdit *LineEdit = new QLineEdit(&messwarn);
        LineEdit->setMinimumWidth(200);
        messwarn.setLayout(new QHBoxLayout);
        messwarn.layout()->addWidget(LineEdit);
        LineEdit->setPlaceholderText("map name");
        int result = messwarn.exec();
        if(LineEdit) {
            if(!LineEdit->text().isEmpty())
            {
                fileName = g_LocalMapPath+QString("/%1").arg(LineEdit->text());
                QDir dir(fileName);
                if(!dir.exists())
                    dir.mkpath(fileName);
            }
        }
        else
            fileName = QFileDialog::getExistingDirectory(this,QStringLiteral("请选择一个文件"),g_LocalMapPath);

        if(result == QMessageBox::Save)
        {
            if(!fileName.isEmpty())
            {
                // 用户选择了一个文件夹，可以在这里进行相应的操作
                qDebug() << "Selected file: " << fileName<<g_CurrentMapID;
                m_MapGraphicsView->slot_Map_Edit("newMapEdit","stopCreateMap");
                ui->actionCreateMap->setText(QString(u8"创建地图"));
                ui->action_mapEdit->setEnabled(true);
                emit sig_NaviSendData("saveCreateMap",fileName.remove(0,fileName.lastIndexOf("/")+1));
                emit sig_getCreatorMapData("stopGetNewCteatorMapImage");
                emit sig_NaviSendData("StratSubscribe","");

                g_CurrentMapID = fileName;
                QTimer::singleShot(2000,this,[this](){
                    emit sig_NaviSendData("stopCreateMap");
                    QString fileName = g_LocalMapPath+QString("/%1").arg(g_CurrentMapID);
                    m_TMSSHConnectWGT->Public_ssh_Pull(g_CurrentMapID,"openMap:"+fileName);
                });
            }
        }
        else if(result == QMessageBox::Discard)
        {
            qDebug()<<"result == QMessageBox::Discard";
            m_MapGraphicsView->slot_Map_Edit("newMapEdit","stopCreateMap");
            ui->actionCreateMap->setText(QString(u8"创建地图"));
            ui->action_mapEdit->setEnabled(true);
            emit sig_NaviSendData("stopCreateMap");
            emit sig_getCreatorMapData("stopGetNewCteatorMapImage");
            emit sig_NaviSendData("StratSubscribe","");

        }
        else if(result == QMessageBox::Cancel)
        {
            qDebug()<<"result == QMessageBox::Cancel";
        }
    }

    ui->action_mapEdit->setChecked(false);
}

void MainWindow::on_lineEdit_MapName_returnPressed()
{
    QMessageBox::StandardButton result = QMessageBox::warning(this,QString(u8"Warning消息框"),QString(u8"是否要修改地图名称为:%1").arg(ui->lineEdit_MapName->text()),
                                                              QMessageBox::Save|QMessageBox::Discard,
                                                              QMessageBox::Save);
    if(result == QMessageBox::Save)
    {
        QDir directory(g_LocalMapPath+QString("/%1").arg(g_CurrentMapID));
        const QFileInfoList &fileInfoList = directory.entryInfoList();
        for (const QFileInfo &fileInfo : fileInfoList) {
            if (fileInfo.isFile())
            { // 检查是否是文件
                qDebug() << "Found file:" <<fileInfo.path()<< fileInfo.fileName()<<g_CurrentMapID;

                if(fileInfo.fileName().indexOf(g_CurrentMapID+".") != -1)
                {
                    if (!QFile::rename(fileInfo.path()+"/"+fileInfo.fileName(),
                                       fileInfo.path()+"/"+fileInfo.fileName().replace(g_CurrentMapID,ui->lineEdit_MapName->text())
                                       )
                        )
                    {
                        qDebug() << "Failed to rename file:";
                    }
                }
            }
        }
        directory.rename(
            g_LocalMapPath+QString("/%1").arg(g_CurrentMapID),
            g_LocalMapPath+QString("/%1").arg(ui->lineEdit_MapName->text())
            );


        QString path = g_LocalMapPath+QString("/%1/%2.yaml").arg(ui->lineEdit_MapName->text(),ui->lineEdit_MapName->text());
        qDebug()<<"map  rename"<<path;
        // 加载YAML文件
        YAML::Node config = YAML::LoadFile(path.toStdString());
        // 修改YAML内容
        QString tsext = g_RemoteMapPath+QString("/%1/%2.pgm").arg(ui->lineEdit_MapName->text(),ui->lineEdit_MapName->text());
        qDebug()<<"map  rename text"<<tsext;
        config["image"] = tsext.toStdString();
        std::ofstream fout(path.toStdString());
        fout << config;
        fout.close();

        QString cmdmapName = g_CurrentMapID;
        m_TMSSHConnectWGT->Pub_executeCmd(QString("mkdir %1/%2").arg(g_RemoteMapPath).arg(ui->lineEdit_MapName->text()));
        g_CurrentMapID = ui->lineEdit_MapName->text();
        m_MapGraphicsView->m_PixmapItem->setData(ItemId,g_CurrentMapID);
        m_TMSSHConnectWGT->Pub_executeCmd(QString("cp %1/%2/%3.pbstream %4/%5/%6.pbstream")
                                              .arg(g_RemoteMapPath,cmdmapName,cmdmapName)
                                              .arg(g_RemoteMapPath,g_CurrentMapID,g_CurrentMapID));
        //修改地图名称，内部拷贝.pbstream，文件太大，防止传输过程中受损。
        QTimer::singleShot(1000,this,[this](){
            m_TMSSHConnectWGT->Public_ssh_Push(g_CurrentMapID);
        });




    }
    else
    {
        ui->lineEdit_MapName->setText(g_CurrentMapID);
    }

}

void MainWindow::on_action_NewLine_triggered(bool checked)
{
    qDebug()<<"MainWindow::on_action_NewLine_triggered"<<checked;
    if(checked)
        m_MapGraphicsView->slot_CurrentAction(Action_DrawLine);
}

void MainWindow::on_action_VirtureWall_triggered(bool checked)
{
    if(checked)
        m_MapGraphicsView->slot_CurrentAction(Action_VirtualWall);
}

void MainWindow::on_action_Eraser_triggered(bool checked)
{
    if(checked)
    {
        QMessageBox messageBox;
        messageBox.setText(QString(u8"请选择橡皮擦颜色？"));
        messageBox.setWindowTitle(QString(u8"橡皮擦选择框"));
        QRadioButton *radioButton1 = new QRadioButton(QString(u8"黑色"));
        QRadioButton *radioButton2 = new QRadioButton(QString(u8"白色"));
        messageBox.setLayout(new QVBoxLayout);
        messageBox.layout()->addWidget(radioButton1);
        messageBox.layout()->addWidget(radioButton2);
        radioButton1->setChecked(true);
        QButtonGroup *buttonGroup = new QButtonGroup(messageBox.layout());
        buttonGroup->addButton(radioButton1, 1);
        buttonGroup->addButton(radioButton2, 2);
        messageBox.exec();
        QRadioButton *checkedButton = qobject_cast<QRadioButton*>(buttonGroup->checkedButton());
        if (checkedButton) {
            // 处理选中的按钮
            QString selectedOption = checkedButton->text();
            // 例如: 如果选项1被选中，输出信息
            if (selectedOption == QString(u8"黑色")) {
                m_MapGraphicsView->slot_CurrentAction(Action_Eraser,"black");
            } else if (selectedOption == QString(u8"白色")) {
                m_MapGraphicsView->slot_CurrentAction(Action_Eraser,"white");
            }
        }
    }
}

void MainWindow::on_action_Select_triggered(bool checked)
{
    qDebug()<<"on_action_Select_triggered="<<checked;
    if(checked)
        m_MapGraphicsView->slot_CurrentAction(Action_NULL);
}

void MainWindow::on_actionChangeMap_triggered()
{
    QMessageBox::StandardButton result = QMessageBox::warning(this,QString(u8"Warning消息框"),QString(u8"是否要修改定位地图为:%1").arg(g_CurrentMapID),
                                                              QMessageBox::Ok|QMessageBox::Discard,
                                                              QMessageBox::Ok);
    if(result == QMessageBox::Ok)
    {
        QString send_data = QString("{\"op\": \"call_servi"
                                    "ce\", \"service\": \"%1\", \"args\": {\"filename\": \"stop\"}};").arg(g_RobotLocalization);
        emit sig_NaviSendData("",send_data);
        send_data = QString("{\"op\": \"call_service\", \"service\": \"%1\", \"args\": {\"filename\": \"%2\"}};").arg(g_RobotLocalization,g_CurrentMapID);
        emit sig_NaviSendData("",send_data);

        // 加载YAML文件
        YAML::Node config = YAML::LoadFile(g_LocalMapPath.toStdString() +"/PLNS.yaml");
        // 修改YAML内容
        config["amr_mapname"] = g_CurrentMapID.toStdString();
        std::ofstream fout(g_LocalMapPath.toStdString() +"/PLNS.yaml");
        fout << config;
        fout.close();
        m_TMSSHConnectWGT->Public_ssh_PushFilePath("/PLNS.yaml");
    }
}

void MainWindow::on_action_pullMap_triggered()
{
    emit sig_NaviSendData("",QString("{\"op\": \"call_service\", \"service\": \"%1\", \"args\": {\"filename\": \"\"}};").arg(g_RobotLocalization));
}

void MainWindow::on_action_addpoint_triggered()
{
    m_MapGraphicsView->slot_CurrentAction(Action_AddPoint);
}

void MainWindow::on_action_Location_triggered(bool checked)
{
    if(m_MapGraphicsView->m_CurrentAction == Action_mapLocation)
        checked = false;
    if(checked)
    {
        m_MapGraphicsView->slot_CurrentAction(Action_mapLocation);
        ui->action_Robot->setChecked(true);
        m_MapGraphicsView->slot_Map_Edit("robotshow","true");
    }
    else
    {
        ui->action_Select->setChecked(true);
        m_MapGraphicsView->slot_CurrentAction(Action_NULL);
    }
}

void MainWindow::on_action_Robot_triggered(bool checked)
{
    if(checked)
        m_MapGraphicsView->slot_Map_Edit("robotshow","true");
    else
        m_MapGraphicsView->slot_Map_Edit("robotshow","false");
}

void MainWindow::on_lineEdit_PointX_returnPressed()
{
    m_MapGraphicsView->slot_Map_Edit("setPointX",ui->lineEdit_PointX->text());
}

void MainWindow::on_lineEdit_PointY_returnPressed()
{
    m_MapGraphicsView->slot_Map_Edit("setPointY",ui->lineEdit_PointY->text());
}

void MainWindow::on_btn_CarPara_clicked()
{
    m_DlgCarPara->exec();
}


void MainWindow::on_btn_LaserPara_clicked()
{
    m_DlgLaserPara->slot_show("lidar");
}


void MainWindow::on_btn_showError_clicked()
{
    m_DlgReportError->exec();
}


void MainWindow::on_btn_vision_clicked()
{
    m_DlgVisionPara->slot_show("vision");
}


void MainWindow::on_lineEdit_localPath_returnPressed()
{
    if(ui->lineEdit_localPath->text().isEmpty())
        return;
    QMessageBox::StandardButton result = QMessageBox::warning(this,tr("Warning消息框"),tr("是否要修改本地地图路径？"),
                                                              QMessageBox::Save|QMessageBox::Cancel,
                                                              QMessageBox::Save);

    if(result == QMessageBox::Save)
    {
        g_LocalMapPath = ui->lineEdit_localPath->text();
        QSettings CfgSet(QString("%1/BaseCfg.ini").arg(g_strExeRoot), QSettings::IniFormat);
        qDebug()<<"11111111111111111"<<QString("%1/BaseCfg.ini").arg(g_strExeRoot);
        CfgSet.setIniCodec("UTF-8");
        CfgSet.setValue("base/localPath",g_LocalMapPath);

    }
    else
    {
        ui->lineEdit_localPath->setText(g_LocalMapPath);
    }
}
void MainWindow::on_pushButton_clicked()
{
    m_DlgIMUPara->slot_show("IMUPara");
}


void MainWindow::on_btn_Task_clicked()
{
    if(ui->btn_Task->text() == QString(u8"发布任务"))
    {
        for(int i=0;i<ui->tableWidget_Task->rowCount();i++)
        {
            if(ui->tableWidget_Task->item(i,0)->text().length() > 0)
            {
                QString data = QString("R\"({\"op\": \"call_service\",\"service\": \"%1\",\"args\":{\"request\": \"%2:%3\",\"mode\": 2}})\";")
                                   .arg(g_RobotRequest_service,g_CurrentMapID,ui->tableWidget_Task->item(i,0)->text());//mode: 1自由导航 2路线导航
                emit sig_NaviSendData("",data);
                break;
            }
        }

        ui->btn_Task->setText(QString(u8"停止任务"));
        ui->tableWidget_Task->setEnabled(false);
    }
    else
    {
        ui->btn_Task->setText(QString(u8"发布任务"));
        ui->tableWidget_Task->setEnabled(true);
    }
}

void MainWindow::on_action_pause_triggered(bool checked)
{
    qDebug()<<"on_action_pause_triggered"<<checked;
    if(checked)
    {
        ui->action_pause->setIcon(QIcon(":/image/image/continue.png"));
        QString data = QString("R\"({\"op\": \"call_service\",\"service\": \"%1\",\"args\":{\"request\": \"stop\",\"mode\": 3}})\";").arg(g_RobotRequest_service);
        emit sig_NaviSendData("",data);
    }
    else
    {
        ui->action_pause->setIcon(QIcon(":/image/image/pause.png"));
        QString data = QString("R\"({\"op\": \"call_service\",\"service\": \"%1\",\"args\":{\"request\": \"continue\",\"mode\": 4}})\";").arg(g_RobotRequest_service);
        emit sig_NaviSendData("",data);
    }
}

void MainWindow::on_action_cancel_triggered()
{
    ui->action_pause->setChecked(false);
    ui->action_pause->setIcon(QIcon(":/image/image/pause.png"));
    QString data = QString("R\"({\"op\": \"call_service\",\"service\": \"%1\",\"args\":{\"request\": \"cancel\",\"mode\": 5}})\";").arg(g_RobotRequest_service);
    emit sig_NaviSendData("",data);

}

void MainWindow::on_action_mapEdit_triggered(bool checked)
{
    qDebug()<<"on_action_mapEdit_triggered"<<checked;
    ui->tab_Point->setEnabled(checked);
    ui->tab_Line->setEnabled(checked);
    ui->tab_map->setEnabled(checked);
    ui->action_Select->setChecked(true);
    m_MapGraphicsView->slot_OpenMapEdit(checked);
    m_MapGraphicsView->slot_CurrentAction(Action_NULL);

    if(checked)
    {
        ui->toolBar_Left->setEnabled(true);
        ui->action_mapEdit->setText("退出编辑");
    }
    else
    {
        ui->toolBar_Left->setEnabled(false);
        ui->action_mapEdit->setText("启用编辑");
        if(!g_CurrentMapID.isEmpty())
            on_actionSaveMap_triggered();
    }
}

void MainWindow::on_radioButton_StartEnd_clicked(bool checked)
{
    qDebug()<<"on_radioButton_StartEnd_clicked="<<checked;
    if(checked)
    {
        QVariantMap dataMap = ui->comboBox_Direct->itemData(0,1).toMap();
        dataMap = dataMap["StartEnd"].toMap();
        QMap<QString,WgtPara*>::iterator it;
        for(it = m_LiniPataMap.begin(); it != m_LiniPataMap.end(); ++it) {
            WgtPara *para = (WgtPara *)(it.value());
            if(dataMap[QString("%1").arg(it.key())].toString().length() > 0
                && dataMap[QString("%1").arg(it.key())].toString() != "NULL")
            {
                para->slot_setPart(dataMap[QString("%1").arg(it.key())].toString());
            }
            else
            {
                para->slot_setPart("NULL");
            }
        }
    }
}

void MainWindow::on_radioButton_endStart_clicked(bool checked)
{
    qDebug()<<"on_radioButton_endStart_clicked="<<checked;
    if(checked)
    {
        QVariantMap dataMap = ui->comboBox_Direct->itemData(0,1).toMap();
        dataMap = dataMap["EndStart"].toMap();
        QMap<QString,WgtPara*>::iterator it;
        for(it = m_LiniPataMap.begin(); it != m_LiniPataMap.end(); ++it) {
            WgtPara *para = (WgtPara *)(it.value());
            if(dataMap[QString("%1").arg(it.key())].toString().length() > 0
                && dataMap[QString("%1").arg(it.key())].toString() != "NULL")
            {
                para->slot_setPart(dataMap[QString("%1").arg(it.key())].toString());
            }
            else
            {
                para->slot_setPart("NULL");
            }
        }
    }
}


void MainWindow::on_pushButton_pullCarPara_clicked()
{
    m_TMSSHConnectWGT->Public_ssh_PullFilePath(g_RemoteMapPath+QString("/PLNS.yaml"));
}


void MainWindow::on_pushButton_2_clicked()
{
    std::vector<std::string> path = m_DirectedGraph->shortestPath("LM2","LM14");
    for(std::string str : path){
        qDebug()<<"path="<<QString::fromStdString(str);
    }
}


void MainWindow::on_lineEdit_pointFind_returnPressed()
{
    if(ui->lineEdit_pointFind->text().isEmpty())
        return;

    m_MapGraphicsView->slot_Map_Edit("ItemViewCenter",ui->lineEdit_pointFind->text());

}

